﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.Communication.Base;
using UtilZ.Dotnet.Ex.Communication.Net.Base;
using UtilZ.Dotnet.Ex.Communication.Net.Tcp;
using UtilZ.Dotnet.Ex.Log;

namespace DotnetWinFormApp
{
    public partial class FTestNetTcpClient : Form
    {
        public FTestNetTcpClient()
        {
            InitializeComponent();
        }

        private void FTestNetTcpClient_Load(object sender, EventArgs e)
        {
            try
            {
                var redirectAppenderToUI = (RedirectAppender)Loger.GetAppenderByName(null, "RedirectToUI");
                if (redirectAppenderToUI != null)
                {
                    redirectAppenderToUI.RedirectOuput += RedirectLogOutput;
                }
            }
            catch (Exception ex)
            {
                Loger.Error(ex);
            }
        }

        private void RedirectLogOutput(object sender, RedirectOuputArgs e)
        {
            logControl.AddLog(e.Item.Content, e.Item.Level);
        }

        private NetTcpClient _tcpClient = null;
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (this._tcpClient == null)
            {
                this._tcpClient = new NetTcpClient(new NetTcpClientInitPara(new FTestNetTcpClientUnpacker(), new IPEndPoint(IPAddress.Parse(txtIP.Text), (int)numPort.Value)));
                this._tcpClient.ConnectChanged += _tcpClient_ConnectChanged;
                this._tcpClient.ConnectAsync();
                return;
            }
        }

        private void _tcpClient_ConnectChanged(object sender, NetConnectedChangedArgs e)
        {
            if (e.Status == ConnectionStatus.Opened)
            {
                Loger.Info("与服务端的连接建立");
            }
            else
            {
                Loger.Warn("与服务端的连接断开");
            }

        }

        private NetTcpListener _tcpListener = null;
        private void btnListen_Click(object sender, EventArgs e)
        {
            if (this._tcpListener == null)
            {
                this._tcpListener = new NetTcpListener(this.AcceptSocket, new NetTcpListenerInitPara((int)numPort.Value, 3));
                this._tcpListener.Start();
                Loger.Info("开始监听");
                return;
            }
            else
            {
                if (this._tcpListener.Accepting)
                {
                    this._tcpListener.Stop();
                    Loger.Info("停止监听");
                }
                else
                {
                    this._tcpListener.Start();
                    Loger.Info("开始监听");
                }
            }
        }


        private List<NetTcpClient> _acceptTcpClientList = new List<NetTcpClient>();
        private void AcceptSocket(AcceptSocketArgs socketArgs)
        {
            var tcpClient = new NetTcpClient(new NetTcpClientInitPara(new FTestNetTcpClientUnpacker(), socketArgs));
            tcpClient.ConnectChanged += Client_ConnectChanged;
            this._acceptTcpClientList.Add(tcpClient);
            Loger.Info($"监听到连接{NetHelper.GetIPPortString(socketArgs.Client.RemoteEndPoint)}");
        }

        private void Client_ConnectChanged(object sender, NetConnectedChangedArgs e)
        {
            if (e.Status == ConnectionStatus.Opened)
            {
                Loger.Info("与客户端的连接建立");
            }
            else
            {
                Loger.Warn("与客户端的连接断开");
                var client = (NetTcpClient)sender;
                client.ConnectChanged -= Client_ConnectChanged;
                client.Dispose();
                this._acceptTcpClientList.Remove(client);
            }

        }

        private void btnDisconectAll_Click(object sender, EventArgs e)
        {
            foreach(var client in this._acceptTcpClientList)
            {
                client.ConnectChanged -= Client_ConnectChanged;
                client.Dispose();
            }
            this._acceptTcpClientList.Clear();
            Loger.Info("已断开所有客户端");
        }
    }

    internal class FTestNetTcpClientUnpacker : UnpackerAbs
    {
        public FTestNetTcpClientUnpacker()
        {

        }

        protected override int PrimitiveUnPackge(IUnpackerPara unpackerPara)
        {
            return ((NetTcpUnpackerPara)unpackerPara).DataLength;
        }
    }
}
